<template>
    <el-card class="card f fv">
        <div class="f fac fpj">
            <div class="title">产品目录</div>
            <div class="operation">
                <el-button type="primary" @click="openDialog(null, '添加')">添加产品</el-button>
            </div>
        </div>
        <!-- 搜索条件 -->
        <el-form style="margin-top: 0.12rem;" :model="data.searchform" :inline="true">
            <el-form-item label="产品名称">
                <el-input clearable style="width: 2rem;" @clear="getList(true)" v-model="data.searchform.name" placeholder="请输入产品名称" />
            </el-form-item>
            <el-form-item label="产品类别">
                <el-select style="width: 2rem;" clearable @change="getList(true)" v-model="data.searchform.category_id"
                    placeholder="请选择产品分类">
                    <el-option v-for="item in data.categoryList" :label="item.name" :value="item.id" />                                 
                </el-select>
            </el-form-item>
            <el-form-item label="供应商">
                <el-select style="width: 2rem;" clearable @change="getList(true)" v-model="data.searchform.supplier_id"
                    placeholder="请选择产品供应商">
                    <el-option v-for="item in data.supplierList" :label="item.name" :value="item.id" />                                 
                </el-select>
            </el-form-item>
            <el-form-item label="状态">
                <el-select style="width: 2rem;" clearable @change="getList(true)" v-model="data.searchform.status"
                    placeholder="请选择产品状态">
                    <el-option label="上架" :value="1" />   
                    <el-option label="下架" :value="0" />                               
                </el-select>
            </el-form-item>
            <el-form-item label="">
                <el-button type="primary" @click="getList(true)">搜索</el-button>
                <el-button type="danger" @click="batchDeleteProduct">批量删除</el-button>
            </el-form-item>
        </el-form>

        <!-- 表格 -->
        <el-table 
            :data="data.tableList" 
            :height="data.tableHeight" 
            v-loading="data.tableLoading" 
            stripe 
            @selection-change="handleSelectionChange"
            class="table">
            <el-table-column type="selection" width="40" />
            <el-table-column prop="name" align="center" label="产品信息">
                <template #default="scope">
                    <div class="f fac fpc">
                        <el-image style="width: 0.8rem; height: 0.8rem; margin-right: 8px;" :src="scope.row.img_url" />
                        <div style="text-align: left;">
                            <div>{{ scope.row.name }}</div>
                            <div class="table-sale">￥{{ parseFloat(scope.row.sale_price).toFixed(2) }}</div>
                            <div class="table-info">单位:{{ scope.row.unit }}</div>
                            <div class="table-info">序号:{{ scope.row.id }}</div>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="cost_price" align="center" label="产品进价">
                <template #default="scope">
                    <span>￥{{ parseFloat(scope.row.cost_price).toFixed(2) }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="stock_num" align="center" label="产品库存">
                <template #default="scope">
                    <span>{{ scope.row.stock_num }}{{ scope.row.unit }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="category_id" align="center" label="产品类别">
                <template #default="scope">
                    {{ data.categoryList.filter(item => item.id === scope.row.category_id)[0]?.name }}
                </template>
            </el-table-column>
            <el-table-column prop="description" align="center" label="产品描述" />
            <el-table-column prop="status" align="center" label="状态">
                <template #default="scope">
                    <el-tag :type="scope.row.status ? 'success' : 'info'">{{ scope.row.status ? '上架' : '下架' }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="supplier_id" align="center" label="供应商">
                <template #default="scope">
                    {{ data.supplierList.filter(item => item.id === scope.row.supplier_id)[0]?.name }}
                </template>
            </el-table-column>
            <el-table-column prop="status" align="center" label="创建时间">
                <template #default="scope">
                    <span>{{ scope.row.create_time && utils.formatDate(new Date(scope.row.create_time).getTime(), 'Y-M-D H:I:S') }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
                <template #default="scope">
                    <span v-if="scope.row.status == 0" class="table-edit" @click="operate(scope.row, 1)">上架</span>
                    <span v-if="scope.row.status == 1" class="table-edit" @click="operate(scope.row, 0)">下架</span>
                    <span class="table-edit" @click="openDialog(scope.row, '编辑')">编辑</span>
                    <span class="table-delete" @click="deleteProduct(scope.row)">删除</span>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination background style="margin-top: 0.16rem;" layout="->, total, sizes, prev, pager, next" :pager-count="5"
            v-model:current-page="data.pageNum" v-model:page-size="data.pageSize"
            :total="data.total" @size-change="getList()" @current-change="getList()" />

        <!-- 抽屉/弹框 -->
        <el-drawer v-model="dialogData.dialogVisible" :title="dialogData.dialogTitle" direction="rtl" @close="closeDialog">
            <div class="content">
                <el-form :model="dialogData.form" label-postion="left" label-width="0.8rem" :rules="dialogData.formRules" hide-required-asterisk ref="refForm">
                    <el-form-item label="产品名称" prop="name">
                        <el-input v-model="dialogData.form.name" placeholder="请输入产品名称" />
                    </el-form-item>
                    <el-form-item label="图片" prop="img_url">
                        <el-upload  
                            v-model:file-list="dialogData.fileList"
                            class="upload-img"                          
                            :action="utils.apiUrl + 'upload/img'"
                            :headers="headers" 
                            accept="image/jpg, image/jpeg, image/png"
                            name="img"
                            list-type="picture-card"
                            :on-success="handleUploadSuccess"
                            :on-remove="handleRemove"  
                            :on-exceed="handleExceed"  
                            :before-upload="beforeUpload"                   
                            :limit="1"
                        >                            
                            <el-icon class="img-uploader-icon"><Plus /></el-icon> 
                            <template #tip>
                                <div class="el-upload__tip text-red">
                                    最多只能上传一张图片哦
                                </div>
                            </template> 
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="产品类别" prop="category_id">
                        <el-select v-model="dialogData.form.category_id"
                            placeholder="请选择产品分类">
                            <el-option v-for="item in data.categoryList" :label="item.name" :value="item.id" />                                 
                        </el-select>
                    </el-form-item>
                    <el-form-item label="产品描述" prop="description">
                        <el-input type="textarea" resize="none" v-model="dialogData.form.description" placeholder="请输入产品描述" />
                    </el-form-item>
                    <el-form-item label="单位" prop="unit">
                        <el-input v-model="dialogData.form.unit" placeholder="请输入单位" />
                    </el-form-item>
                    <el-form-item label="库存" prop="stock_num">
                        <el-input v-model.number="dialogData.form.stock_num" :min="1" type="number" placeholder="请输入库存数量">
                            <template #append>{{ dialogData.form.unit }}</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="进价" prop="cost_price">
                        <el-input v-model.number="dialogData.form.cost_price" :min="0" type="number" placeholder="请输入产品进价">
                            <template #append>元</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="售价" prop="sale_price">
                        <el-input v-model.number="dialogData.form.sale_price" :min="0" type="number" placeholder="请输入产品售价">
                            <template #append>元</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="供应商" prop="supplier_id">
                        <el-select v-model="dialogData.form.supplier_id"
                            placeholder="请选择产品供应商">
                            <el-option v-for="item in data.supplierList" :label="item.name" :value="item.id" />                                 
                        </el-select>
                    </el-form-item>
                    <el-form-item label="是否上架" prop="status">
                        <el-switch v-model="dialogData.form.status" :active-value="1" :inactive-value="0" />
                    </el-form-item>
                </el-form>
                <div class="footer">
                    <el-button type="primary" @click="submit">确定</el-button>
                    <el-button @click="closeDialog">取消</el-button>
                </div>
            </div>
        </el-drawer>

    </el-card>
</template>

<script setup>
import { ref, onMounted, reactive, watchEffect } from 'vue'
import http from '@/api/home'
import utils from '@/utils/utils'
import { Plus } from '@element-plus/icons-vue'


const refForm = ref()

const headers = {
    Authorization: sessionStorage.token
}

// 自定义校验规则(库存、价格)
const validateNum = (rule, value, callback) => {
    if (value == '' || value == undefined) {
        callback(new Error('请输入值'))
    } else if (value < 0) {
        callback(new Error('输入的值必须大于等于0'))
    } else {
        callback()
    }
}

// 数据集
const data = reactive({
    // 搜索表单对象
    searchform: {},
    // 表格数据
    tableList: [],
    // 表格高度
    tableHeight: 0,
    // 表格加载
    tableLoading: false,
    // 分页 
    pageNum: 1,
    pageSize: 20,
    total: 0,
    // 产品分类
    categoryList: [],
    // 供应商列表
    supplierList: [],
    // 勾选的产品
    chooseProduct: []
})

// 弹框
const dialogData = reactive({
    // 是否显示
    dialogVisible: false,
    // 标题
    dialogTitle: '',
    // 表单数据 
    form: {},
    // 校验规则
    formRules: {
        name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
        img_url: [{ required: true, message: '请上传图片', trigger: 'change' }],
        category_id: [{ required: true, message: '请选择产品类别', trigger: 'change' }],
        unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
        stock_num: [{ required: true, validator: validateNum, trigger: 'blur' }],
        cost_price: [{ required: true, validator: validateNum, trigger: 'blur' }],
        sale_price: [{ required: true, validator: validateNum, trigger: 'blur' }],
        supplier_id: [{ required: true, message: '请选择供应商', trigger: 'change' }],
    },
    // 图片列表
    fileList: []
})

onMounted(() => {
    getCategoryList()
    getSupplierList()
    getList()
})
// 获取产品分类
const getCategoryList = () => {
    http.categoryList().then(res => {
        data.categoryList = res.data
    })
}
// 获取供应商
const getSupplierList = () => {
    http.productSupplier().then(res => {
        data.supplierList = res.data
    })
}
// 获取列表
const getList = (reset = false) => {
    if (reset) data.pageNum = 1
    data.tableLoading = true
    http.productList({
        ...data.searchform,
        pageNum: data.pageNum,
        pageSize: data.pageSize
    }).then(res => {
        data.tableLoading = false
        data.tableList = res.data.records
        data.total = res.data.total
    }).finally(() => {
        data.tableLoading = false
    })
}
// 上下架
const operate = (row, status) => {
    data.tableLoading = true
    http.operate({
        id: row.id,
        operation: status
    }).then(res => {
        data.tableLoading = false
        ElMessage({ type: 'success', message: res.message })
        getList()
    })
}
// 打开对话框
const openDialog = (row, title) => {
    dialogData.dialogVisible = true
    if (row) {
        dialogData.form = { ...row }
        // 图片列表
        if (dialogData.form.img_url) {
            dialogData.fileList = [{ name: row.img_url, url: row.img_url }]
        } else {
            dialogData.fileList = []
        }
    } else {
        dialogData.form = {}
    }
    dialogData.dialogTitle = title
}

// 关闭对话框
const closeDialog = () => {
    dialogData.dialogVisible = false; 
    refForm.value.resetFields(); 
    dialogData.form = {}
    dialogData.fileList = []
}

// 上传图片
const handleUploadSuccess = (response, uploadFile, uploadFiles) => {
    dialogData.form.img_url = response.imgUrl
    // dialogData.form.img_url = 'https://element-plus.gitee.io/images/plant-1.png'
}

// 移除上传的图片
const handleRemove = (uploadFile, uploadFiles) => {
    dialogData.form.img_url = ''
    dialogData.fileList = []
}

// 超出上传限制
const handleExceed = () => {
    ElMessage.warning('最多只能上传一张图片哦')
}

// 上传之前
const beforeUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('只能上传图片哦')
        return false
    }
    return true
}

//提交
const submit = () => {
    refForm.value.validate((valid) => {
        if (valid) {            
            if (dialogData.dialogTitle == '添加') {                
                http.productAdd(dialogData.form).then(res => {
                    ElMessage({ type: 'success', message: res.message })
                    dialogData.dialogVisible = false
                    getList()
                })
            } else {
                http.productUpdate(dialogData.form).then(res => {
                    ElMessage({ type: 'success', message: res.message })
                    dialogData.dialogVisible = false
                    getList()
                })
            }
        }
    })
}

// 删除
const deleteProduct = (data) => {
    ElMessageBox.confirm(
        '是否删除该产品?',
        '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        http.productDelete({ id: data.id }).then(res => {
            ElMessage({ type: 'success', message: res.message })
            getList()
        })
    })
}

// 批量删除
const batchDeleteProduct = () => {
    if (data.chooseProduct.length === 0) {
        ElMessage({ type: 'warning', message: "请选择要删除的产品" })
        return
    }
    ElMessageBox.confirm(
        '是否删除选中的产品?',
        '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        let ids = data.chooseProduct.map(item => item.id)
        http.batchDeleteProduct({ ids }).then(res => {
            ElMessage({ type: 'success', message: res.message })
            getList()
        })
    })
}

// 勾选的产品
const handleSelectionChange = (val) => {
    data.chooseProduct = val
}


// 设置表格高度
const setTableHeight = () => {
    let tableH = 320 // 距离下方的距离 
    let tableHeightDetail = window.innerHeight - tableH
    if (tableHeightDetail <= 400) {
        data.tableHeight = 400
    } else {
        data.tableHeight = window.innerHeight - tableH 
    }
}
watchEffect(() => setTableHeight())

</script>

<style lang="scss" scoped>
.card {
    box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.2);
    margin-top: 0.14rem;
    height: calc(100vh - 0.68rem - 0.7rem);

    .title {
        font-size: 0.2rem;
        font-weight: bold;
        color: #000;
        padding-bottom: 0.1rem;
        border-bottom: 4px solid $ncpColor;
    }

    .role-input {
        width: 2rem;
        margin-right: 0.2rem;
    }

    .table {
        width: 100%;
        .table-sale {
            color: $helpColor;
        }
        .table-info {
            color: #9CA3AF;
            font-size: 0.12rem;
        }   
    }

    .table-edit {
        color: $otherColor;
        margin-right: 0.2rem;
        cursor: pointer;

        &:hover {
            text-decoration: underline;
        }
    }

    .disabled {
        pointer-events: none;
        opacity: 0.8;
    }

    .table-delete {
        color: $helpColor;
        cursor: pointer;

        &:hover {
            text-decoration: underline;
        }
    }

    :deep(.el-drawer__title) {
        font-size: 0.16rem;
    }
    .content {
        position: relative;
        height: 100%;
        .upload-img .img {
            width: 1rem;
            height: 1rem;
            display: block;
        }
        :deep(.upload-img .el-upload) {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
            &:hover {
                border-color: var(--el-color-primary);
            }
        }
        .el-icon.img-uploader-icon {
            font-size: 0.28rem;
            color: #8c939d;
            width: 1rem;
            height: 1rem;
            text-align: center;
        }

        .footer {
            position: absolute;
            bottom: 0;
            left: 0;
        }
    }

}
</style>